from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
# Create your views here.
from django.contrib.auth.hashers import make_password, check_password
from myadmin import models
from django.core.urlresolvers import reverse
#引入绘图模块
from PIL import Image, ImageDraw, ImageFont
#引入随机函数模块
import random



# 加入购物车
def cartadd(request):

    # 非会员购买
    gid = request.GET['gid']
    num = int(request.GET['num'])

    # 获取商品对应的 详细信息
    ob = models.Goods.objects.get(id=int(request.GET['gid']))
    xi = {'id':ob.id,"num":num,'title':ob.title,'pic':ob.pic,'price':ob.price}

    # 获取购物车数据
    data = request.session.get('buygoods',{})

    # 判断 加到购物车的 物品在不在原商品中
    if gid in data:
        data[gid]['num'] = int(data[gid]['num']) + num
    else:
        # 修改数据
        data[gid] = xi


    # data 字典里 id为键 信息为值            { {id为键:信息为值} , {id为键 信息为值} , {id为键 信息为值}}
    request.session['buygoods'] = data
    # 获取  data 中有几个商品
    l = len(data)
    request.session['len'] = {"changdu":l}
    return JsonResponse({"jieguo":1,"shangpinliang":l})

# 购物车页面
def cartindex(request):

    return render(request,'home/cart.html')

# 购物车商品删除
def cardelete(request,gid):
    # 获取请求里的 gid 数据 删除
    data = request.session.get('buygoods',{})
    del data[gid]
    request.session['buygoods'] = data

    request.session['len'] = {"changdu":len(data)}


    return HttpResponse('<script>location.href="'+reverse('myhome_cartindex')+'"</script>')

# 购物车 商品数量 加减 
def cartedit(request):
    # gid = request.GET.get('gid')
    # num = int(request.GET.get('num'))

    # # 获取购物车数据
    # data = request.session['buygoods']
    # # 修改购买数量
    # data[gid]['num'] = num
    # # 把购物车从重新存入 session
    # request.session['buygoods'] = data

    '''
    {
    '28': {'price': 449.0, 'pic': '/static/pics/goodimg/1537403009.780014573468.png', 'title': 'POP 真无线蓝牙耳机', 'id': 28, 'num': 3},
    '25': {'price': 899.0, 'pic': '/static/pics/goodimg/1537282016.898742292813.png', 'title': '魅蓝 Note6', 'id': 25, 'num': 1}, 
    '23': {'price': 799.0, 'pic': '/static/pics/goodimg/1537281925.751062472621.png', 'title': '魅蓝 6T', 'id': 23, 'num': 3}, 
    '18': {'price': 2698.0, 'pic': '/static/pics/goodimg/1537281602.55770725449.png', 'title': '魅族 16th', 'id': 18, 'num': 3}
    }


    '''
    # 准备工作
    jie = request.GET.dict()
    # 对数据 + - 符号
    fuhao = jie['edit']
    # 当前商品数量
    num   = int(jie['num'])
    # 获取修改数量的 商品
    s1 = request.session.get('buygoods',None)
    # 讲请求中字符串类型 转成int类型
    gid = jie['gid']
    s_zhi = s1[gid]['num']
    # 获取该商品价格
    jiage = s1[gid]['price']

    
    # 开始处理
    # 判断  +    还是  - 
    if fuhao == '+':
        s_zhi += 1
    else:
        if(s_zhi <= 1):
           s_zhi = 1
        else:
            s_zhi -= 1
    xiaoji = jiage * s_zhi
    # 修改后 讲s1存入 请求    
    s1[gid]['num'] = s_zhi
    request.session['buygoods'] = s1

    return JsonResponse({"jieguo":1,"liang":s_zhi,"xiaoji":xiaoji})
    
# 清空购物车
def cartclear(request):

    try:
        request.session['len'] = {"changdu":0}
        request.session['buygoods'] = {}
    except Exception as e:
        pass      

    return HttpResponse("清空购物车")

# 确认订单
def orderconfirm(request):
    # 接受传递数据
    ids = request.GET.get('ids')
    # 获取购物车数据
    buygoods = request.session.get('buygoods')

    ids = ids.split(',')
    data = {}
    for x in ids:
        data[x] = buygoods[x]

    context = {'info':data}
    print(data)

    '''
    {'18': {'id': 18, 'num': 10, 'title': '魅族 16th', 
    'pic': '/static/pics/goodimg/1537281602.55770725449.png', 
    'price': 2698.0}}
    '''

    # 获取当前用户的所有收货地址
    adds = models.Address.objects.filter(uid=request.session['VipUser']['uid'])

    # 分配数据
    context = {'info':data,'adds':adds}

    return render(request,'home/order/confirm.html',context)
    # return render(request,'home/order/confirm.html')

# 添加地址
def addressinsert(request):
    # 接受数据
    data = request.GET.dict()
    # 获取用户对象
    data['uid'] = models.Users.objects.get(id=request.session['VipUser']['uid'])


    # 判断是否为默认
    if data['status'] == '1':
        data['status'] = True
        # 把其他的地址改为非默认
        obs = models.Address.objects.filter(uid=data['uid'])
        for x in obs:
            x.status = False
            x.save()

    # 执行添加
    ob = models.Address.objects.create(**data)

    return JsonResponse({'error':0,'msg':'地址添加成功'})

# 生成订单
def ordercreate(request):
    # 接受数据
    ids = request.POST.get('ids')
    ids = ids.split(',')
    addid = request.POST.get('addid')
    print(ids,addid)

    # 生成订单
    orderdata = {}
    orderdata['uid'] = models.Users.objects.get(id=request.session['VipUser']['uid'])
    orderdata['aid'] = models.Address.objects.get(id=addid)
    orderdata['totalprice'] = 0
    ob = models.Order.objects.create(**orderdata)


    # 获取购物车数据
    cart = request.session['buygoods']
    totalprice = 0
    # 订单详情
    for x in ids:   
        x = int(x)
        # 创建订单详情
        goods = models.Goods.objects.get(id=x)

        res = models.OrederInfo()            
        res.orderid = ob
        res.goodsid = goods
        
        res.num = cart[str(x)]['num']
        res.price = goods.price
        res.save()
        # 删除购物车已购买商品  
        del cart[str(x)]        
        # 运算总价
        totalprice += res.price*res.num
        # 扣库存
        goods.num -= res.num
        goods.save()

    # 从新计算购物车以买商品种类长度
    yuanchang = int(request.session['len']['changdu'])
    maichang = len(ids)
    xinchang = yuanchang - maichang
    request.session['len']['changdu'] = xinchang

    # 购物车数据重新存入session
    request.session['buygoods'] = cart
    ob.totalprice = totalprice
    ob.save()

    # 跳转到支付页面



    return HttpResponse('<script>alert("请支付");location.href="/order/buy/'+str(ob.id)+'/"</script>')

# 支付
def orderbuy(request,oid):
    
    # 根据订单id获取订单信息
    ob = models.Order.objects.get(id=oid)

    context = {'order':ob}

    # 显示一个支付页面

    return render(request,'home/order/buy.html',context)

# 支付成功
def orderbuysuccess(request,oid):
    # 获取当单号 确认是否支付成功
    ob = models.Order.objects.get(id=oid)
    ob.status = 1
    ob.save()
    return render(request,'home/order/success.html')

# 支付失败
def quxiaozhifu(request,oid):
    # 获取当单号 确认是否支付成功
    ob = models.Order.objects.get(id=oid)
    ob.status = 3
    ob.save()
    return render(request,'home/index.html')


# 我的订单
def myorder(request):
    # 查询当前用户的订单
    orderlist = models.Order.objects.filter(uid=request.session['VipUser']['uid'])

    # 接受页面请求
    ye_status = request.GET.get('status','-1')
    if ye_status == '-1':
        # 获取当前用户对象的所有订单
        
        pass
    # 0未付款 1未付款 代发货 2已收货 3取消订单
    elif ye_status == '0':
        orderlist = orderlist.filter(status=0)
    elif ye_status == '1':
        orderlist = orderlist.filter(status=1)
    elif ye_status == '2':
        orderlist = orderlist.filter(status=2)
    elif ye_status == '3':
        orderlist = orderlist.filter(status=3)

    centext = {'orderlist':orderlist,'biao':ye_status}
    return render(request,'home/center/myorder.html',centext)

# 地址管理
def dizhi(request):
    # 获取该用户的所有地址 
    quanbudizhi = models.Address.objects.filter(uid=request.session['VipUser']['uid'])

    # 在请求前面加字符 d(删除)| s(修改)
    shanid = request.GET.get('did',None)
    if shanid == None:
        pass
    else:
        # 判断是  删除 还是 修改
        if shanid[0:1] == 'd':
            # 删除选择的地址
            id = int(shanid[1:])
            os = quanbudizhi.get(id=id)            
            os.delete()
        else:
            # 修改默认地址
            id = int(shanid[1:])
            os = quanbudizhi.get(id=id)
            for i in quanbudizhi:
                i.status = 0
                i.save()
            os = quanbudizhi.get(id=id)
            os.status = 1
            os.save()
            
    quanbudizhi = models.Address.objects.filter(uid=request.session['VipUser']['uid'])
    

    centext = {'dizhi':quanbudizhi}
    return render(request,'home/center/dizhi.html',centext)

# 个人信息
def xinxi(request):
    # 获取当前用户 id
    Vid = request.session['VipUser']['uid']
    # 查询数据库中 该 用户信息
    us = models.Users.objects.get(id=int(Vid))


    data = {"info":us}
    return render(request,"home/center/xinxi.html",data)

# {'phone': '123456', 'username': '123456', 'uid': 27, 'status': 0}

# request.session['VipUser'] = {'uid':ku.id,
# 'username':ku.username,'phone':ku.phone,'status':ku.state}

# 个人信息修改
def xinxixiugai(request):
    uid = request.GET.get('uid')
    # 查询数据库中 该 用户信息
    us = models.Users.objects.get(id=uid)
    data = {"info":us}
    return render(request,"home/center/xinxixiugai.html",data)

# 个人信息更新
def xinxigengxin(request):
    data = request.POST.dict()
    # {'id': '31', 'sex': '1', 'pic': '', 'age': '55', 
    # 'csrfmiddlewaretoken': 'ndGH0Dwm6kC86dneKWu2vkXZjdB0070Lh7IdETxPTUBW7LwbcBdH4zfZ6T5jKrNS', 
    # 'email': '55', 'username': 'sjy', 'phone': '17319272731'}
    data.pop('csrfmiddlewaretoken')

    # return HttpResponse("asdjk")
    uid = data['id']

    # 获取页面传过来的头像信息
    myfile = request.FILES.get('pic',None)   
    if myfile == None:
        tuname = None
    else:
        # 获取图片名字
        tuname = str(myfile).split(' ')[0]
    # 获取要修改的id
    ku = models.Users.objects.get(id=uid)
    # 数据库表中 图片的名字
    n = ku.pic
    ku_name = ku.pic
    # 如果没改图片 tuname = None
    if tuname == None:
        # 如果没改图片 不做任何操作
        pass
    else:
        if n == '/static/pics/user.jpg':
            pass
        else:
            pass
            # # 否则   删除文件中的图片
            # os.remove("./"+n) 
        # 把新图片 编辑放入数据库
        # 图片名字创建
        myfile = request.FILES.get('pic',None)
        from myadmin.views import IndexViews
        ku.pic = IndexViews.uploads(myfile)
        
    ku.username = data['username']
    ku.phone = data['phone']
    ku.email = data['email']
    ku.sex = data['sex']
    ku.age = data['age']
    ku.save()

    return HttpResponse('<script>location.href="'+reverse('myhome_xinxi')+'"</script>')


